<template>
	<view class="poster">
		<image src="https://ywtmp.hnwytkj.com/static/images/bj2.png" mode="" class="bj"></image>
		<view class="poster-content">
			<view v-if="info.userProfileDO" class="section">
				<view class="section-top">
					<view>{{info.userProfileDO.realName || '姓名：未填写'}}</view>
					<view class="avatar">
						<image v-if="info.userProfileDO.avatar" :src="info.userProfileDO.avatar" mode="scaleToFill"></image>
						<open-data v-else type="userAvatarUrl"></open-data>
					</view>
				</view>
				<view class="section-bottom">
					<view class="section-bottom-content">
						<view class="item-box">
							<view>{{info.userProfileDO.jobTitle|| '职务：未填写'}}</view>
							<view class="mt24">{{info.companyProfileDO.companyName || '公司名称：未填写'}}</view>
							<view class="item-section mt36">
								<image src="https://ywtmp.hnwytkj.com/static/images/phone.png" mode="aspectFit"></image>
								<text>{{info.userProfileDO.phoneNumber || '未填写'}}</text>
							</view>
							<view class="item-section mt25">
								<image src="https://ywtmp.hnwytkj.com/static/images/wx.png" mode="aspectFit"></image>
								<text>{{info.userProfileDO.wechatId || '未填写'}}</text>
							</view>
							<view class="item-section mt26 address">
								<image src="https://ywtmp.hnwytkj.com/static/images/address.png" mode="aspectFit"></image>
								<text>{{info.companyProfileDO.address.address || '未填写'}}</text>
							</view>
						</view>
						<view class="qrcode">
							<image :src="qrcode || 'https://ywtmp.hnwytkj.com/static/images/img.png'" mode=""></image>
						</view>
						<view class="btn-box">
							<view class="share-btn">
								<image src="https://ywtmp.hnwytkj.com/static/images/user.png" mode=""></image>
								<text>分享给朋友</text>
								<button v-if="info.userProfileDO && info.userProfileDO.realName && info.companyProfileDO.companyName" open-type="share"></button>
								<button v-else @tap="share"></button>
							</view>
							<view class="share-btn" @tap="shareToFriend">
								<image src="https://ywtmp.hnwytkj.com/static/images/friend.png" mode=""></image>
								<text>分享到朋友圈</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="btn" @tap="saveToPhone">保存图片</view>
		</view>
		<!-- <l-painter ref="painter">...code</l-painter> -->
		<!-- <hch-poster ref="hchPoster" @cancel="handleCancel" :posterData.sync="posterData" @previewImage='previewImage' /> -->
		<poster ref="poster" :list="list" background-color="#FFF" :width="750" :height="1334"
		            @on-success="posterSuccess" @on-error="posterError"></poster>
	</view>
</template>

<script>
	import http from '@/utils/http.js'
	import Poster from '../../components/zhangyuhao-poster/Poster.vue'
	export default {
		components: {
			Poster
		},
		data() {
			return {
				info: {},
				list: [],
				posterUrl: '',
				qrcode: ''
			}
		},
		onLoad() {
			this.getData()			
		},
		methods: {
			share() {
				if (!this.info.userProfileDO.realName) {
					uni.showModal({
						title: '提示',
						content: '您还未完善个人信息，无法分享',
						confirmText: '去完善',
						success:  (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pagesA/edit/editEnterpriseInformation'
								})							
							}
						}
					})
					return false
				}
				if (!this.info.companyProfileDO.companyName) {
					uni.showModal({
						title: '提示',
						content: '您还未完善企业信息，无法分享',
						confirmText: '去完善',
						success:  (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pagesA/edit/editProfile'
								})							
							}
						}
					})
					return false
				}
			},
			posterSuccess(url) {
				this.posterUrl = url
				console.log(url)
				uni.hideLoading()
				if (this.saveToPhotosAlbum) {
					uni.saveImageToPhotosAlbum({
						filePath: url,
						success: function () {
							console.log('save success');
						}
					});
				} else {
					wx.showShareImageMenu({
					  path: this.posterUrl
					})
				}			
			},
			posterError(err) {
				uni.hideLoading()
				uni.showToast({
					title: '生成海报失败',
					icon: 'error'
				})
			},
			confirm(e) {
				
			},
			shareToFriend() {
				this.saveToPhotosAlbum = false
				this.save().then(res => {
					// wx.downloadFile({
					//   // url: 'https://res.wx.qq.com/wxdoc/dist/assets/img/demo.ef5c5bef.jpg',
					//   url: this.posterUrl,
					//   success: (res) => {
					//     wx.showShareImageMenu({
					//       path: res.tempFilePath
					//     })
					//   }
					// })
					// debugger
					// wx.showShareImageMenu({
					//   path: this.posterUrl
					// })
				})				
			},
			// 将 Base64 转为临时文件并上传
			uploadBase64Image(base64Data) {
			  return new Promise((resolve, reject) => {
			    // 1. 移除 Base64 头部
			    const base64 = base64Data.replace(/^data:image\/\w+;base64,/, '');
			    
			    // 2. 生成临时路径
			    const filePath = `${wx.env.USER_DATA_PATH}/${Date.now()}.png`;
			    
			    // 3. 写入临时文件
			    const fs = wx.getFileSystemManager();
			    fs.writeFile({
			      filePath,
			      data: base64,
			      encoding: 'base64',
			      success: () => {
			        // 4. 执行上传
					const userId = uni.getStorageSync('userId');
			        uni.uploadFile({
			          url: `https://ywtmp.hnwytkj.com/app-api/infra/file/upload?path=images/${userId}/wxa-qrcode.jpg`, //仅为示例，非真实的接口地址
			          filePath,
			          name: 'file',
			          success: (uploadRes) => {
			            // 5. 上传成功后删除临时文件（可选）
			            try { fs.unlinkSync(filePath); } catch(e) {}
			            resolve(JSON.parse(uploadRes.data));
			          },
			          fail: (err) => {
			            try { fs.unlinkSync(filePath); } catch(e) {}
			            reject('上传失败: ' + err.errMsg);
			          }
			        });
			      },
			      fail: (writeErr) => {
			        reject('文件写入失败: ' + writeErr.errMsg);
			      }
			    });
			  });
			},			
			getQrcode() {
				const userId = uni.getStorageSync('userId');
				http({
					url: 'member/social-user/wxa-qrcode',
					method: 'post',
					data: {
						path: 'pagesA/share/card',
						// scene: `id=${userId}&encrypted=${this.info.userProfileDO.level}`
						scene: `id=${userId}`
					}
				}).then(res => {
					if(res.code === 0) {
						this.qrcode = `data:image/png;base64,${res.data}`
						// 使用示例						
						this.uploadBase64Image(this.qrcode)
						  .then(res => console.log('上传成功', res))
						  .catch(err => console.error(err));
					}
				})
			},
			getData() {
				http({
					url: 'card/user-profile/get',
				}).then(res => {
					if(res.code === 0) {
						res.data.companyProfileDO.address = (res.data.companyProfileDO.address ? JSON.parse(res.data.companyProfileDO.address) : {})
						res.data.companyProfileDO.industry = (res.data.companyProfileDO.industry ? JSON.parse(res.data.companyProfileDO.industry) : {})
						this.info = res.data
						this.getQrcode()
					}
				})
			},
			saveToPhone() {
				this.saveToPhotosAlbum = true
				this.save()
			},
			save() {
				// this.$refs.painter.canvasToTempFilePathSync({
				//   fileType: "jpg",
				//   // 如果返回的是base64是无法使用 saveImageToPhotosAlbum，需要设置 pathType为url
				//   pathType: 'url',
				//   quality: 1,
				//   success: (res) => {
				//     console.log(res.tempFilePath);
				//     // 非H5 保存到相册
				//     // H5 提示用户长按图另存
				//     uni.saveImageToPhotosAlbum({
				//         filePath: res.tempFilePath,
				//         success: function () {
				//             console.log('save success');
				//         }
				//     });
				//   },
				// });
				// this.$refs.hchPoster.posterShow()
				 // 赋值需要渲染的信息
				uni.showLoading({
					title: '生成海报中...',
					mask: true
				})	
				const userId = uni.getStorageSync('userId');
				this.list = [{
						type: 'image',
						// path替换成你自己的图片，注意需要在小程序开发设置中配置域名
						path: 'https://ywtmp.hnwytkj.com/static/images/bj2.png',//this.info.userProfileDO.avatar,
						x: 0,
						y: 0,
						width: 750,
						height: 750
					},
					{
						type: 'text',
						text: this.info.userProfileDO.realName || '',
						x: 20,
						y: 760,
						size: 24,
						color: '#000'
					},
					{
						type: 'text',
						text: this.info.companyProfileDO.companyName || '',
						x: 20,
						y: 800,
						size: 24,
						color: '#000'
					},
					{
						type: 'text',
						text: `${this.info.companyProfileDO.industry.label || ''} ${this.info.companyProfileDO.serviceScope || ''}`,
						x: 20,
						y: 860,
						size: 24,
						color: '#000'
					},
					{
						type: 'text',
						text: this.info.userProfileDO.phoneNumber || '',
						x: 20,
						y: 900,
						size: 24,
						color: '#000'
					},
					{
						type: 'textarea',
						text: this.info.companyProfileDO.address.address || '',
						x: 20,
						y: 940,
						width: 900,
						height: 160,
						size: 24,
						color: '#000'
					},
					{
						type: 'image',
						path: (this.qrcode ? `https://ywtmp.hnwytkj.com/static/images/${userId}/wxa-qrcode.jpg` : 'https://ywtmp.hnwytkj.com/static/images/img.png'),
						// path: 'https://ywtmp.hnwytkj.com/static/images/img.png', 
						x: (750 - 200) / 2,
						y: 1000,
						width: 200,
						height: 200
					},
					{
						type: 'text',
						width: 160,
						height: 150,
						x: (750 - 160) / 2,
						y: 1220,
						text: '长按识别二维码',
						size: 24,
						color: '#000'
					}
				];
				return new Promise((resolve, reject) => {
					// 生成图片
					this.$nextTick(() => {
						// 要放在$nextTick()里，不然会空白
						this.$refs.poster.create();	
						resolve()
					})
				})				
			},
			saveShare() {
				const userId = uni.getStorageSync('userId')
				if (userId) {
					http({
						url: 'card/user-profile/like/update',
						method: 'put',
						data: {
							userId,
							type: 1
						}
					})
				}
			},
		},
		onShareAppMessage() {
			const userId = uni.getStorageSync('userId')
			this.saveShare()
			return {
			   title: '您好，这是我的名片，请惠存',
			   // path: '/pagesA/share/card?id=' + userId, // 分享的路径
			   path: `/pagesA/share/card?id=${userId}&encrypted=${this.info.userProfileDO.level}`, // 分享的路径
			   imageUrl: `https://ywtmp.hnwytkj.com/static/images/${userId}/shareCard.jpg?t=${Math.random()}` // 可选，分享图片的路径
			}
		},
		// onShareTimeline() {
		// 	const userId = uni.getStorageSync('userId')
		//     return {
		//       title: '您好，这是我的名片，请惠存',
		//       query: 'id=' + userId,
		// 	  path: '/pagesA/share/card?id=' + userId,
		//       // imageUrl: this.posterUrl 
		// 	  imagesUrl: '/static/images/share.jpg'
		//     }
		// },
	}
</script>

<style lang="scss" scoped>
	.poster {
		background: #F0F0F4;
		min-height: 100vh;
		padding-bottom: calc(20rpx + var(--safe-area-inset-bottom));
		box-sizing: border-box;
		.bj {
			width: 100%;
			height: 1025rpx;
			position: absolute;
			z-index: 1;
			left: 0;
			top: 0;
		}
		.poster-content {
			padding: 635rpx 30rpx 0;
			position: relative;
			z-index: 9;
			.section {
				background: rgba(0, 0, 0, 0.5);
				border-radius: 20rpx;
				.section-top {
					height: 117rpx;
					position: relative;
					font-family: PingFang SC;
					font-weight: bold;
					font-size: 40rpx;
					color: #FFFFFF;
					line-height: 117rpx;
					padding-left: 42rpx;
					.avatar {
						width: 150rpx;
						height: 150rpx;
						background: #FFFFFF;
						border-radius: 50%;
						border: 6rpx solid #90BCFF;
						position: absolute;
						z-index: 10;
						right: 40rpx;
						top: 40rpx;
						// padding: 6rpx 0 0 6rpx;
						box-sizing: border-box;
						overflow: hidden;
						image {
							width: 100%;
							height: 100%;
							border-radius: 50%;
						}
					}
				}
				.section-bottom {
					// height: 590rpx;
					min-height: 600rpx;
					background: #FFFFFF;
					border-radius: 20rpx;
					// background-image: url('/static/images/pic.png');
					// background-size: 262rpx 278rpx;
					// background-position: 388rpx 152rpx;
					position: relative;
					.section-bottom-content {
						padding: 40rpx 20rpx;
						font-weight: 500;
						font-size: 28rpx;
						color: #333333;
						position: relative;
						z-index: 9;
						.item-box {
							padding: 0 20rpx;
							.item-section {
								display: flex;
								// align-items: center;
								font-weight: bold;
								line-height: 48rpx;
								image {
									width: 48rpx;
									height: 48rpx;
									margin-right: 30rpx;
								}
								text {
									flex: 1;
								}
								&.address {
									line-height: 50rpx;
								}
							}
						}						
						.qrcode {
							text-align: center;
							margin: 24rpx 0;
							image {
								// width: 130rpx;
								// height: 130rpx;
								width: 260rpx;
								height: 260rpx;
							}
						}
						.btn-box {
							display: flex;
							align-items: center;
							justify-content: space-between;
							.share-btn {
								width: 314rpx;
								height: 70rpx;
								display: flex;
								align-items: center;
								justify-content: center;
								background: #E6ECFF;
								border-radius: 20rpx;
								font-weight: 500;
								font-size: 26rpx;
								color: #4B73FF;
								position: relative;
								image {
									width: 42rpx;
									height: 42rpx;
									margin-right: 12rpx;
								}
								button {
									position: absolute;
									width: 100%;
									height: 100%;
									top: 0;
									left: 0;
									opacity: 0;
								}
							}
						}
					}
				}
			}
			.btn {
				height: 90rpx;
				background: #4B73FF;
				border-radius: 20rpx;
				margin-top: 30rpx;
				font-weight: bold;
				font-size: 28rpx;
				color: #FFFFFF;
				line-height: 90rpx;
				text-align: center;
			}
		}
	}
</style>